package com.ai.bmg.bmgwebboot.test.zk;


/**
 * 功能描述
 *
 * @author cWX1142527
 * @since 2023年01月18日
 */
public class Java_53_最大子数组的和 {
    public static void main(String args[]) {
        int[] nums = new int[]{-2,-1,-3,-4,-1,-2,-1,-5,-4};
        int max = maxSubArray(nums);
        System.out.println(max);
    }

    public static int maxSubArray(int[] nums) {
        if (nums.length <= 1) {
            return nums.length;
        }
        int maxSum = nums[0];
        int tempSum = nums[0];
        for (int i = 1; i < nums.length; i++) {
            // 之前的和为负数时，抛弃之前的和，从当前数据进行填加
            if (tempSum < 0) {
                tempSum = nums[i];
            } else {
                tempSum = tempSum + nums[i];
            }
            maxSum = tempSum < maxSum ? maxSum : tempSum;
        }
        return maxSum;
    }
}